# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

package require tcltest 2
namespace import tcltest::*

source "testlib.tcl"

test readlink_denies_outside_sandbox "Test that readlink(2) fails outside of the sandbox" \
    -setup {
        file link -symbolic link .
        [setup [list deny /]]
    } \
    -cleanup {
        file delete -force link
        [expect [list "$cwd/link"]]
    } \
    -body {exec -ignorestderr -- ./readlink link 2>@1} \
    -result "readlink(link): No such file or directory"

test readlink_succeeds_inside_sandbox "Test that readlink(2) succeeds inside of the sandbox" \
    -setup {
        file link -symbolic link readlink.c
        # note the link target is outside of the sandbox ...
        [setup [list deny "$cwd/readlink.c" allow "$cwd"]]
    } \
    -cleanup {
        file delete -force link
        # ... but this does not produce a violation
        [expect {}]
    } \
    -body {exec -ignorestderr -- ./readlink link 2>@1} \
    -result "readlink.c"

test readlink_succeeds_on_missing_file "Test that readlink(2) does not care whether the target exists" \
    -setup {
        # Tcl's file link -symbolic will fail on links targets that don't exist
        exec -ignorestderr -- ln -s this_file_does_not_exist link
        [setup [list allow /]]
    } \
    -cleanup {
        file delete -force link
        [expect {}]
    } \
    -body {
        exec -ignorestderr -- ./readlink link 2>@1
    } \
    -result "this_file_does_not_exist"

test readlink_succeeds_when_uninitialized "Test that readlink(2) succeeds outside of the sandbox when darwintrace is uninitialized" \
    -setup {
        file link -symbolic link .
        [setup [list deny /]]
    } \
    -cleanup {
        file delete -force link
        [expect {}]
    } \
    -body {
        set ::env(DARWINTRACE_UNINITIALIZE) 1
        set output [exec -ignorestderr -- ./readlink link 2>@1]
        unset ::env(DARWINTRACE_UNINITIALIZE)
        return $output
    } \
    -result "."

cleanupTests
